#!/bin/bash
source /etc/profile


:>output.error.log


ip_mediator1=10.47.61.114

IP_VAR=ip_mediator1
remote_host=admin@10.47.61.114

#定义mvn
mvn="/opt/jenkins_slave/tools/hudson.tasks.Maven_MavenInstallation/maven3.3.9/bin/mvn"
temp_dir="/tmp/web_agent"
agent_dir="/mytijian/agent/client/webservice"
hospital_dir="/mytijian/agent/hospitals"

#代码编译方法
function build(){
    echo "+++++代码编译+++++"
    $mvn clean install -Pver
}

#获取版本号
if [ -f "pom.xml" ];then
    version=`awk '/<version>[^<]+<\/version>/{gsub(/<version>|<\/version>/,"",$1);print $1;exit}' pom.xml`
else
    echo "!!!!! pom.xml 不存在!!!!!">>output.error.log
    exit 1
fi

#agent发布方法
function deploy(){
    echo "+++++发布开始+++++"

    if [[ "$version" =~ ^(-?|\+?)[0-9]+(\.?[0-9]+)(\.?[0-9]+)?$ ]]
    then
       echo "pass"
    else
       echo "版本格式不合法:$version,请修改pom中的版本信息(版本支支持数字格式)" >> output.error.log && exit 1
    fi
    
    ssh ${remote_host} "ls /mytijian/agent/client/webservice/$version"
    if [ $? != 0 ];then
        ssh ${remote_host} "mkdir /mytijian/agent/client/webservice/$version" >>/dev/null
    else
        ssh ${remote_host} "rm -rf /mytijian/agent/client/webservice/$version/*" >>/dev/null
    fi

    #[ $? != 0 ]&& exit 0
    echo "======copy control and mediator-agent war======"
    for file in `find $WORKSPACE -type f |grep -E "\.war$"`
    do  	
        scp $file ${remote_host}:/mytijian/agent/client/webservice/$version
    done
    echo "+++++发布结束+++++"
}

#医院agent打包方法
function pack(){
    echo "+++++打包开始+++++"
    rm -rf MediatorAgentConfig
    git clone -b develop git@gitee.com:mytj/MediatorAgentConfig.git
    
    [ $? != 0 ]&&exit 1
    
    #清理临时目录
    ssh  ${remote_host} [ -d "$temp_dir" ]

    if [ $? = 0 ];then
        ssh  ${remote_host} "rm -rf $temp_dir/*"
    else
        ssh  ${remote_host} "mkdir ${temp_dir}"
        if [ $? != 0 ];then
            echo "create ${temp_dir} failed">>/tmp/alert
            exit 1
        fi
    fi

    #解压war包到临时目录
    ssh ${remote_host} "mkdir ${temp_dir}/mediator-agent && unzip $agent_dir/$version/client-agent-$version.war -d $temp_dir/mediator-agent"
    
    #替换配置文件
    scp $WORKSPACE/MediatorAgentConfig/hospital/${hospitalid}/config.properties ${remote_host}:${temp_dir}/mediator-agent/WEB-INF/classes
    
    #移动agent包到医院目录
    ssh ${remote_host} "cd $temp_dir && zip -r mediator-agent.zip * && mv mediator-agent.zip $hospital_dir/$hospitalid"
    ssh ${remote_host} "cd $temp_dir && rm -rf mediator-agent"
    echo "+++++打包结束+++++"
}

if [ $deploy = "true" ];then
    build
    deploy
fi

if [ "X$hospitalid" != "X" ];then
    pack
fi